package cn.uestc.labhms.modules.hms.controller;

import cn.uestc.labhms.common.annotation.SysLog;
import cn.uestc.labhms.common.utils.R;
import cn.uestc.labhms.common.validator.group.RegisterGroup;
import cn.uestc.labhms.modules.hms.entity.Vo.UserPermsVo;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.service.UserPermService;
import cn.uestc.labhms.modules.hms.service.UserService;
import cn.uestc.labhms.modules.sys.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserPermService userPermService;

    @PostMapping("/register")
    @SysLog("用户注册")
    public R register(@Validated(value = RegisterGroup.class) @RequestBody SysUserEntity sysUserEntity) {
        userService.register(sysUserEntity);
        return R.ok("注册成功");
    }
    @GetMapping("/get/user/list/perms")
    @SysLog("查看用户查看权限列表")
    @RequiresPermissions("hms:hms_user_perm:list")
    public R userListPerms(@RequestParam(value = "id", required = false) Integer userId) {
        if (userId == null) {
            log.warn("没有输入具体用户id，无法得知该用户权限，此操作可能为前端误操作，可忽略");
            return R.ok("没有输入具体用户id，无法得知该用户权限");
        }
        List<String> listPerm = userPermService.getListPerm(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("listPerms", listPerm);
        return R.ok().put("data", map);
    }
    @GetMapping("/get/user/update/perms")
    @SysLog("查看用户修改权限列表")
    @RequiresPermissions("hms:hms_user_perm:list")
    public R userUpdatePerms(@RequestParam("id") Integer userId) {
        List<String> updatePerm = userPermService.getUpdatePerm(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("updatePerms", updatePerm);
        return R.ok().put("data", map);
    }
    @PostMapping("/put/hms_user_perm/{type}")
    @SysLog("设置用户权限")
    @RequiresPermissions("hms:hms_user_perm:update")
    public R setUserPerm(@RequestBody(required = false) @Validated UserPermsVo userPermsVo, @PathVariable("type") String type) {
        if (type == null || (!"list".equals(type) && !"update".equals(type))) {
            throw new HMSException("type不能为空，只能是list或者update中的一个");
        }
        userPermService.setUserPerms(userPermsVo.getUserId(), userPermsVo.getPerms(), type);
        return R.ok();
    }
}
